package leetcode.code1888;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int minFlips(String s) {
		char[] cs = s.toCharArray();
		int len = cs.length;
		// 至此 偶数位置上 0的个数
		int[] o0 = new int[len];
		// 至此 奇数位置上 0的个数
		int[] j0 = new int[len];
		// 至此 偶数位置上 1的个数
		int[] o1 = new int[len];
		// 至此 奇数位置上 1的个数
		int[] j1 = new int[len];
		char c = cs[0];
		if (c == '0') {
			o0[0] = 1;
		} else {
			o1[0] = 1;
		}
		for (int i = 1; i < len; i++) {
			c = cs[i];
			if (c == '0') {
				if ((i & 1) == 0) {
					o0[i] = o0[i - 1] + 1;
					j0[i] = j0[i - 1];
				} else {
					o0[i] = o0[i - 1];
					j0[i] = j0[i - 1] + 1;
				}
				o1[i] = o1[i - 1];
				j1[i] = j1[i - 1];
			} else {
				if ((i & 1) == 0) {
					o1[i] = o1[i - 1] + 1;
					j1[i] = j1[i - 1];
				} else {
					o1[i] = o1[i - 1];
					j1[i] = j1[i - 1] + 1;
				}
				o0[i] = o0[i - 1];
				j0[i] = j0[i - 1];
			}
		}
		int ans = Math.min(o0[len - 1] + j1[len - 1], o1[len - 1] + j0[len - 1]);
		for (int i = 0; i < len; i++) {
			boolean flag = ((i & 1) == 1 && (len & 1) == 1) || ((i & 1) == 0 && (len & 1) == 0);// 前面有偶数个
			boolean flag1 = (i & 1) == 0;
			int po0 = flag ? j0[i] : o0[i];
			int pj0 = flag ? o0[i] : j0[i];
			int po1 = flag ? j1[i] : o1[i];
			int pj1 = flag ? o1[i] : j1[i];
			int so0 = flag1 ? j0[len - 1] - j0[i] : o0[len - 1] - o0[i];
			int sj0 = flag1 ? o0[len - 1] - o0[i] : j0[len - 1] - j0[i];
			int so1 = flag1 ? j1[len - 1] - j1[i] : o1[len - 1] - o1[i];
			int sj1 = flag1 ? o1[len - 1] - o1[i] : j1[len - 1] - j1[i];
			ans = Math.min(ans, Math.min(po0 + so0 + pj1 + sj1, pj0 + sj0 + po1 + so1));
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(10, this.minFlips("1110000001101010101010101111110000"));
		H.compare(1, this.minFlips("01100"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
